# -*- coding:utf-8 -*-
import getopt
import locale
import os
import platform
import pysvn
import shutil
import socket
import struct
import sys
import fcntl
from pylib import SuperxGit

from pylib.utils import *
from pylib.svn_utils import *
from pylib.git_utils import *

GIT_REPO_URL = 'https://git.oschina.net/c0der/superx.git'

WORKSPACE_PATH = os.path.dirname(os.path.abspath(__file__))
WORKSPACE_COOCAASDK_PATH = '%s/CoocaaSDK' % WORKSPACE_PATH
WORKSPACE_COOCAASDKCONFIG_PATH = '%s/CoocaaSDKConfig' % WORKSPACE_PATH
WORKSPACE_VERSION_PROPERTIES = '%s/version.properties' % WORKSPACE_PATH

APPSTORE_PATH = '%s/AppStore'
SERVER_BUILD_GRADLE = '%s/build.gradle.server'
APPFRAMEWORKPACKAGE_PATH = '%s/LiteApp/LiteAppFrameworkPackage'
SERVER_MANIFEST = '%s/AndroidManifest.xml.server'

BUILD_OUT_APKS_PATH = '%s/%s/build/outputs/apk'
BUILD_OUT_MAPPING_PATH = '%s/%s/build/outputs/mapping'

FTP_RELEASE_PATH = 'ftp/projects/git_superx/Release'

my_platform = platform.system().lower()


def config_work_on_server(work_on_server, path):
    appstore_path = APPSTORE_PATH % path
    #     appframework_path = APPFRAMEWORKPACKAGE_PATH % path

    # copy build.gradle
    dest_gradle = '%s/build.gradle' % appstore_path
    if work_on_server == True:
        src_gradle = SERVER_BUILD_GRADLE % appstore_path
        if 'linux' in my_platform:
            os.system("cp %s %s" % (src_gradle, dest_gradle))
        elif 'windows' in my_platform:
            os.system("copy %s %s" % (src_gradle, dest_gradle))


# # copy appstore's AndroidManifest.xml
#     dest_manifest = '%s/AndroidManifest.xml' % appstore_path
#     if work_on_server == True:
#         src_manifest = SERVER_MANIFEST % appstore_path
#         if 'linux' in my_platform:
#             os.system("cp %s %s" % (src_manifest, dest_manifest))
#         elif 'windows' in my_platform:
#             os.system("copy %s %s" % (src_manifest, dest_manifest))
#     
#     # copy appframework's AndroidManifest.xml
#     dest_manifest = '%s/AndroidManifest.xml' % appframework_path
#     if work_on_server == True:
#         src_manifest = SERVER_MANIFEST % appframework_path
#         if 'linux' in my_platform:
#             os.system("cp %s %s" % (src_manifest, dest_manifest))
#         elif 'windows' in my_platform:
#             os.system("copy %s %s" % (src_manifest, dest_manifest))

# def checkout_trunk(work_on_server):
#     log("now start checkout Trunk")
#     svn_checkout(TRUNK_PATH, WORKSPACE_TRUNK_PATH)
#     log("now complete checkout Trunk")
#     setup_py = '%s/setup.py' % WORKSPACE_TRUNK_PATH
#     os.system("python %s" % setup_py)
#     config_work_on_server(work_on_server, WORKSPACE_TRUNK_PATH)
#
#
# def checkout_libs():
#     log("now start checkout Libs")
#     svn_checkout(LIBS_PATH, WORKSPACE_LIBS_PATH)
#     log("now complete checkout Libs")
#
#
# def checkout_branch(branch, work_on_server):
#     log("now start checkout Branch%s" % branch)
#     checkout_coocaasdk()
#     branch_path = '%s/%s' % (BRANCH_PATH, branch)
#     workspace_branch_path = '%s%s' % (WORKSPACE_BRANCH_HEADER, branch)
#     svn_checkout(branch_path, workspace_branch_path)
#     config_work_on_server(work_on_server, workspace_branch_path)
#     log("now complete checkout Branch%s" % branch)
#
#     setup_branch(branch)


def setup_branch(branch):
    SuperxGit.branch(branch)
    SuperxGit.pull(GIT_REPO_URL, branch)
    # git_switch_branch(GIT_REPO_URL, WORKSPACE_PATH, branch)

    # workspace_branch_path = ""


# if 'trunk' == branch.lower():
#     branch = 'Trunk'
#     workspace_branch_path = WORKSPACE_TRUNK_PATH
# else:
#     workspace_branch_path = '%s%s' % (WORKSPACE_BRANCH_HEADER, branch)
# setup_py = '%s/setup.py' % workspace_branch_path
# os.system("python %s" % setup_py)


def get_build_version(project):
    version_major = 0
    version_minor = 0
    version_build = 0
    file_object = open('%s/%s' % (WORKSPACE_VERSION_PROPERTIES, project), 'r')
    lines = file_object.readlines()
    log(lines)
    file_object.close()
    for line in lines:
        kv = line.split('=')
        if 'VERSION_MAJOR' in kv[0]:
            version_major = int(kv[1])
        elif 'VERSION_MINOR' in kv[0]:
            version_minor = int(kv[1])
        elif 'VERSION_BUILD' in kv[0]:
            version_build = int(kv[1])
    return version_major, version_minor, version_build


# def update_build_version(build_path, version, build_version, svn_revision):
#     build_gradle_file = '%s/build.gradle' % (APPSTORE_PATH % build_path)
#     major_version = version.split('.')[0]
#     minor_version = version.split('.')[1]
#     file_object = open(build_gradle_file, 'r')
#     lines = file_object.readlines()
#     log(lines)
#     file_object.close()
#     flag = 0
#     pos = 0
#     for line in lines:
#         if flag == 2:
#             break;
#         if 'versionCode' in line:
#             flag += 1
#             # ABBCCCCC
#             v = int(major_version) * 10000000
#             v += int(minor_version) * 100000
#             v += int(build_version)
#             log(v)
#             lines[pos] = '        versionCode %d \n' % v
#         elif 'versionName' in line:
#             flag += 1
#             lines[pos] = '        versionName \"%s.%s.%s(%s)\" \n' % (major_version, minor_version, build_version, svn_revision)
#         pos += 1
#     file_object = open(build_gradle_file, 'w')
#     file_object.writelines(lines)
#     file_object.close()

def release_apks(build_path, project):
    out_apks_path = BUILD_OUT_APKS_PATH % (build_path, project)
    apks = os.listdir(out_apks_path)
    for apk in apks:
        apk_file = "%s/%s" % (out_apks_path, apk)
        if apk_file.endswith(".apk") == False:
            os.remove(apk_file)
        elif apk_file.find("unaligned") >= 0:
            os.remove(apk_file)
        elif apk_file.find("release") <= 0:
            os.remove(apk_file)
    return out_apks_path


def move_to_ftp(apks_path, project, version, build_version, revision):
    out_path = '%s/%s/%s.%s.%s' % (project, version, version, build_version, revision)
    path = '%s/Release/%s' % (WORKSPACE_PATH, out_path)
    if not os.path.exists(path):
        os.makedirs(path)
    apks = os.listdir(apks_path)
    for apk in apks:
        file_name = apk
        #         file_name = apk.replace("version.apk", "%s.%s_%s.apk" % (version, build_version, svn_revision))
        #         os.rename('%s/%s' % (apks_path, apk), '%s/%s' % (apks_path, file_name))
        _apk = '%s/%s' % (path, file_name)
        open(_apk, "wb").write(open('%s/%s' % (apks_path, file_name), "rb").read())
    return path, out_path


def setup_build_project(path, project):
    file_object = open('%s/settings.gradle' % path, 'r')
    lines = file_object.readlines()
    log(lines)
    file_object.close()
    lines[0] = 'include \':%s\'\n' % project
    file_object = open('settings.gradle', 'w')
    file_object.writelines(lines)
    file_object.close()


def get_ip_address(ifname):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    return socket.inet_ntoa(fcntl.ioctl(
        s.fileno(),
        0x8915,  # SIOCGIFADDR
        struct.pack('256s', ifname[:15]))
                            [20:24])


def backup_mapping(f, t):
    shutil.copytree(f, t)
    # for root, dirs, files in os.walk(f, True):
    #     for eachfile in files:
    #         shutil.copy(os.path.join(root, eachfile), t)


def build_project(branch, projects):
    # build_path = ''
    # if 'trunk' == branch.lower():
    #     build_path = WORKSPACE_TRUNK_PATH
    # else:
    #     build_path = '%s%s' % (WORKSPACE_BRANCH_HEADER, branch)
    revision = SuperxGit.pull(GIT_REPO_URL, branch)[0:7]
    build_path = WORKSPACE_PATH
    # update_build_version(build_path, version, build_version, svn_revision);

    # os.chdir(build_path)
    os.system("gradle clean")
    for project in projects:
        log('ready to build %s' % project)
        try:
            out_apks_path = BUILD_OUT_APKS_PATH % (build_path, project)
            files = os.listdir(out_apks_path)
            for _file in files:
                file_path = "%s/%s" % (out_apks_path, _file)
                os.remove(file_path)
        except Exception as err:
            log(str(err))

        # setup_build_project(build_path, project);
        os.system("gradle assembleRelease -p %s" % project)

        major, minor, build = get_build_version(project)
        apks_path = release_apks(build_path, project)
        release_path, out_path = move_to_ftp(apks_path, project, '%d.%d' % (major, minor), build, revision)

        try:
            backup_mapping(BUILD_OUT_MAPPING_PATH % (build_path, project), '%s/mapping' % release_path)
        except Exception as err:
            log(str(err))
        subject = '%s ver:%d.%d.%d(git@%s) 编译完成' % (project, major, minor, build, revision)
        content = '下载地址:ftp://%s/%s/%s' % (get_ip_address('em1'), FTP_RELEASE_PATH, out_path)
        to = 'luyuxiang@skyworth.com,liqiwen@skyworth.com,luwei@skyworth.com,tengliang@skyworth.com,xufukang@skyworth.com,tangsijing@skyworth.com,hushuang@skyworth.com,yanrongyan@skyworth.com'
        mail(subject, content, to)

        # svn_commit_file(WORKSPACE_VERSION_PROPERTIES, 'update project build.version')


def Usage():
    print('cp.py usage:')
    print(
        '    --build       编译工作目录下的指定分支版本下的指定工程(,隔开)，如 编译trunk下的Hall和AppStore co.py --build trunk:AppStore,Hall；编译2.3分支的Hall co.py --build 2.3:Hall')
    print('    -s            设置工作环境为编译服务器，如果当前init或者branch的版本之后需要在服务器完成自动编译，则加上此项，无此项则默认为本地工作环境')
    print('    --help        显示本提示')


# def init_workspace(work_on_server):
#     checkout_libs()
#     checkout_coocaasdk()
#     checkout_trunk(work_on_server)

def setup_coocaasdk():
    log("now start setup coocaasdk")

    file_object = open('%s/ccsdk.config' % WORKSPACE_COOCAASDKCONFIG_PATH, 'r')
    lines = file_object.readlines()
    log(lines)
    file_object.close()
    for line in lines:
        kv = line.split('=')
        path = "%s/%s" % (WORKSPACE_COOCAASDK_PATH, kv[0])
        log('check out %s from %s to %s' % (kv[0], kv[1], path))
        _url = get_svn_url(path)
        log('exist svn_url：%s   current %s' % (_url, kv[1]))
        if _url.strip() == kv[1].strip():
            svn_update(path)
        else:
            if 'linux' in my_platform:
                os.system("rm -r %s" % path)
            elif 'windows' in my_platform:
                os.system("rd /s /q %s" % path)
            svn_checkout(kv[1].strip(), path)

    if 'linux' in my_platform:
        os.system("cp -r CoocaaSDKConfig/. ./CoocaaSDK")
    elif 'windows' in my_platform:
        os.system("xcopy CoocaaSDKConfig CoocaaSDK /s /e /y")
    log("now complete checkout coocaasdk")


def setup_gradle():
    if 'linux' in my_platform:
        os.system("cp settings.gradle.conf settings.gradle")
    elif 'windows' in my_platform:
        os.system("xcopy settings.gradle.conf settings.gradle /s /e /y")


def main(argv):
    opts, args = getopt.getopt(argv[1:], 's', ['init', 'help', 'build='])
    if len(opts) == 0:
        Usage()
        sys.exit(2)

    work_on_server = False

    for o, a in opts:
        if o in ('-s'):
            work_on_server = True

    for o, a in opts:
        if o in ('--help'):
            Usage()
            sys.exit(1)
        elif o in ('--init'):
            setup_gradle()
            setup_coocaasdk()
            sys.exit(1)
        # elif o in ('--branch'):
        #     project = a
        #     checkout_branch(project, work_on_server)
        #     sys.exit(1)
        elif o in ('--build'):
            bp = a.split(':')
            branch = bp[0]
            projects = bp[1].split(',')
            log('build branch:%s' % branch)
            log('build projects:%s' % projects)
            # os.system('git pull %s %s' % (GIT_REPO_URL, branch))
            setup_branch(branch)
            setup_coocaasdk()
            build_project(branch, projects)
            sys.exit(1)
        else:
            log('unhandled option')
            sys.exit(3)


if __name__ == '__main__':
    reload(sys)
    sys.path.append(WORKSPACE_PATH)
    sys.setdefaultencoding('utf8')
    if 'linux' in my_platform:
        setlocale()
    # shutil.copytree('/home/lu/workspace/skyworth/SuperX/Workspace/B2.6/AppStore/assets', '/home/lu/aaaaa', False, )
    main(sys.argv)
